﻿using Microsoft.AspNetCore.Mvc;
using JESAI.Caching;
using JESAI.Core.Extensions;
using JESAI.Core.Randoms;
using JESAI.Core.VerifyCodes;
using JESAI.Framework.Filters;
using SqlSugar;
using System;
using System.Linq;
using System.Threading.Tasks;
using JESAI.Core.Util.Conversions;
using JESAI.Framework.Mvc;
using JESAI.Application.Abstractions.Dtos;
using Microsoft.AspNetCore.Authorization;

namespace Bucket.Admin.WebApi.Controllers
{
    /// <summary>
    /// 工具
    /// </summary>
    [ApiController]
    [IgnoreResultHandlerAttribute]
    public class ToolController : ControllerBase
    {
        private readonly CacheManager _cacheManager;
        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="cacheManager"></param>
        public ToolController(CacheManager cacheManager)
        {
            _cacheManager = cacheManager;
        }

        /// <summary>
        /// 图形验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet("/Tool/ValidateCode")]
        [AllowAnonymous]
        public async Task<IActionResult> ValidateCode(string guid, int width = 100, int height = 32)
        {
            if (guid.IsEmpty())
                throw new Exception("请输入用户标识");
            var code = Randoms.CreateRandomValue(4, false);
            var st =  VerifyCode.CreateByteByImgVerifyCode(code, width, height);
           
            _cacheManager.Set($"ImgCode_{code}", code, new TimeSpan(0, 5, 0));
            return File(st, "image/jpeg");
        }

        /// <summary>
        /// 图形验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet("/Tool/ValidateCodeStr")]
        [AllowAnonymous]
        public async Task<BaseOutput> ValidateCodeStr(string guid, int width = 100, int height = 32)
        {
            if (guid.IsEmpty())
                throw new Exception("请输入用户标识");
            var code = Randoms.CreateRandomValue(4, false);
            var st = VerifyCode.CreateByteByImgVerifyCode(code, width, height);

            _cacheManager.Set($"ImgCode_{code}", code, new TimeSpan(0, 5, 0));
            return new BaseOutput<string> { Data = "data:image/jpg;base64," + Base64Converter.ToBase64String(st) };
        }
    }
}